package cn.netshop.system.filter;

import cn.netshop.system.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 *鉴权过滤器，用于验证token
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求request
        ServerHttpRequest request = exchange.getRequest();
        //获取响应response
        ServerHttpResponse response = exchange.getResponse();
        //获取请求的url
        String path = request.getURI().getPath();
        //判断如果是注册或者登录请求则放行
        if(path.contains("/admin/login")||path.contains("/admin/add")){
           return chain.filter(exchange);
        }
        //获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        //判断有无token
        if(StringUtils.isEmpty(token)){
            //请求头中无token，拒绝访问
            //响应状态码，访问没有权限
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回
            return response.setComplete();
        }
        //请求头中存在token
        //解析token
        try {
            Claims claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            //解析令牌出错
            e.printStackTrace();
            //响应状态码，访问没有权限
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
